<template>
  <van-nav-bar title="商品详情" left-text="" left-arrow @click-left="goBack" @click-right="isShare = true">
    <template #right>
      <van-icon name="ellipsis" size="18" />
    </template>
  </van-nav-bar>
  <!-- 分享面板 -->
  <van-share-sheet v-model:show="isShare" title="立即分享给好友" :options="Sharelist" />
  <!-- 轮播图 -->
  <van-swipe :autoplay="3000" lazy-render>
    <van-swipe-item v-for="(item, index) in info.thumbs_list" :key="index">
      <van-image height="220" width="100%" :src="item" fit="cover" />
    </van-swipe-item>
  </van-swipe>
  <div class="detailbox">
    <h4>{{ info.name }}</h4>
    <div class="price" style="color: rgb(238, 10, 36); font-size: 22px">
      <em>单独购买￥</em>{{ info.price }} | <em>拼团价格￥</em>{{ info.team }}
      <em style="float: right; color: rgb(183, 183, 191)">库存992件</em>
    </div>
  </div>
  <div class="allkbox"></div>
  <div class="info_choice">
    <!-- Sku 商品规格 -->
    <div class="commodity" @click="SkuShow = true">
      <div class="opt">
        <div class="title wanl-gray">选择</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>尺码</span>
              <span>颜色</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray">
        <img src="/assets/images/go.png" />
      </div>
    </div>
    <!-- 服务 -->
    <div class="commodity" @click="showServe = true">
      <div class="opt">
        <div class="title wanl-gray">服务</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>7天无理由退款</span>
              <span>·</span>
              <span>24小时内发货</span>
              <span>·</span>
              <span>假一赔十</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray">
        <img src="/assets/images/go.png" />
      </div>
    </div>
  </div>
  <div class="clear"></div>
  <div class="allkbox"></div>
  <div class="clear"></div>
  <!-- 参数和评价 -->
  <div class="detailbox_2">
    <van-tabs v-model:active="active" type="card" color="#ee0a24">
      <van-tab title="产品参数">
        <!-- 产品参数 -->
        <div class="rate" v-html="info.content"></div>
      </van-tab>
      <van-tab title="商品评价">
        <!-- 商品评价 -->
        <div class="rate">
          <div class="rate-header">
            <div class="rate-score">
              <h4>与描述相符</h4>
              <strong>{{ Number.isInteger(rateavg) ? `${rateavg}.0` : rateavg }}</strong>
            </div>
            <div class="rate-graph">
              <van-rate v-model="rateavg" readonly allow-half size="30" gutter="5" />
            </div>
          </div>
          <div class="rate-content" v-for="item in rateInfo" :key="item.id">
            <div>
              <div class="review-box">
                <div class="review-item">
                  <div class="from-whom">
                    <div class="avatar">
                      <img :src="item.business.avatar_text" alt="" />
                    </div>
                    <div class="name">{{ item.business.nickname }}</div>
                  </div>
                  <div class="review-details">
                    <div class="content">{{ item.comment }}</div>
                    <div>
                      <van-field name="avatar" label="">
                        <template #input>
                          <van-uploader v-model="item.thumbs_list" multiple :max-count="0" :disabled="false"
                            :deletable="false" />
                        </template>
                      </van-field>
                    </div>
                    <div class="time">{{ item.comtime_text }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div>
              <!-- <div class="rate-empty">该商品还没有人写评价呢</div> -->
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
  <div class="clear"></div>
  <!-- 协议条款 -->
  <van-action-sheet v-model:show="showServe" title="协议条款">
    <div class="ProductTip">
      三、我们如何使用信息 <br />
      四、我们如何共享信息<br />
      五、我们如何转让信息<br />
      六、我们如何公开披露信息<br />
      七、一般储存期限<br />
      八、我们如何确保您的信息安全<br />
      九、您能做什么<br />
      十、我们如何处理未成年人的个人信息<br />
      十一、您的个人信息的存储地点<br />
      十二、本隐私权政策不适用的范围<br />
      十三、本隐私权政策如何更新<br />
      十四、联系我们<br />
    </div>
  </van-action-sheet>

  <!--  商品SKU -->
  <van-sku ref="SkuRef" v-model="SkuShow" stepper-title="购买数量" :sku="sku" :goods="goods" :goods-id="proid"
    :properties="properties" @buy-clicked="onBuyClicked" @add-cart="addCart">
    <!-- 自定义 sku actions -->
    <template #sku-actions="props">
      <div class="van-sku-actions">
        <!-- 直接触发 sku 内部事件，通过内部事件执行 props 回调 -->
        <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">
          加入购物车
        </van-button>
        <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
        <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">
          单独购买
        </van-button>

        <van-button square size="large" type="danger" @click="teamlist">
          参与拼团
        </van-button>

        <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
        <van-button square size="large" type="danger" @click="teamAdd">
          发起拼团
        </van-button>
      </div>
    </template>
  </van-sku>

  <!-- 底部操作栏 -->
  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" @click="onCustomer" />
    <van-action-bar-icon icon="cart-o" text="购物车" :badge="info.count" @click="toPages" />
    <van-action-bar-icon :icon="isCollected ? 'shop-collect-o' : 'shop-o'" :text="isCollected ? '已收藏' : '收藏'"
      @click="onCollection" />
    <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
  </van-action-bar>
</template>

<script setup>
import { showToast } from "vant";
import VanSku from "vant-sku";
import "vant-sku/dist/index.css";
const { proxy } = getCurrentInstance();
const LoginUser = reactive(proxy.$cookies.get("LoginUser"));
import { showSuccessToast } from "vant";
const isShare = ref(false);
const showServe = ref(false);
const Sharelist = [
  [
    { name: "微信", icon: "wechat" },
    { name: "朋友圈", icon: "wechat-moments" },
    { name: "微博", icon: "weibo" },
    { name: "QQ", icon: "qq" },
  ],
  [
    { name: "复制链接", icon: "link" },
    { name: "分享海报", icon: "poster" },
    { name: "二维码", icon: "qrcode" },
    { name: "小程序码", icon: "weapp-qrcode" },
  ],
];
const proid = ref(proxy.$route.query.proid ?? 0);
const info = ref({});

// 商品SKU
const SkuShow = ref(false);
const sku = ref({});
const properties = ref([]);
const goods = ref({});
const SkuRef = ref(null)
const goBack = () => {
  proxy.$router.go(-1);
};
onBeforeMount(() => {
  getProductInfoData();
  getRateInfoData();
});
const isCollected = ref(false);
const getProductInfoData = async () => {
  let result = await Api.ProductInfo({
    proid: proid.value,
    busid: LoginUser.id ?? 0,
  });

  if (result.code == 1) {
    let ProductData = result.data.productinfo;
    let SkuData = result.data.sku;
    let PropertiesData = result.data.properties;
    isCollected.value = result.data.collection;
    info.value = ProductData;
    sku.value = SkuData;
    properties.value = Object.values(PropertiesData);
    goods.value = {
      picture: ProductData.thumbs_text,
    };
  }
};
// 定义一个状态来跟踪是否已收藏

const onCollection = async () => {
  let result = await Api.ProductCollection({
    proid: proid.value,
    busid: LoginUser.id,
  });
  if (result.code == 1) {
    console.log(result);
    showSuccessToast({
      message: result.msg,
      // 切换收藏状态
    });
    isCollected.value = !isCollected.value;
  } else {
    showSuccessToast(result.msg);
  }
};
const onCustomer = () => {
  proxy.$router.push("/product/customer");
};
const addCart = async (skuData) => {
  SkuShow.value = false;

  if (JSON.stringify(LoginUser) == "{}") {
    toast("未登陆，请先去登陆");
    proxy.$router.push("/business/login");
  }

  let selectedNum = skuData.selectedNum;

  if (selectedNum <= 0) {
    error("数量不能为小于0");
    return false;
  }

  let attrs = [];

  // 有商品属性
  if (properties.value.length > 0) {
    let properties = skuData.selectedSkuComb.properties;
    properties.forEach((item, index) => {
      console.log(item.v[0]);
      if (item.v) {
        attrs.push(item.v[0].id);
      }
      return false;
    });
  }

  let data = {
    busid: LoginUser.id,
    proid: proid.value,
    nums: selectedNum,
    attrs: attrs.toString(),
  };

  let result = await Api.CartAdd(data);
  if (result.code == 1) {
    success({
      message: result.msg,
      // onClose: () => {
      //     proxy.$router.push('/business/index')
      // }
    });
  } else {
    error(result.msg);
  }
};
const toPages = () => {
  proxy.$router.push("/product/cart");
};
const onBuyClicked = async (skuData) => {
  console.log(skuData);
  SkuShow.value = false;
  if (JSON.stringify(LoginUser) == "{}") {
    toast("未登陆，请先去登陆");
    proxy.$router.push("/business/login");
  }
  let selectedNum = skuData.selectedNum;
  // if (selectedNum <= 0) {
  //     error('数量不能为小于0');
  //     return false;
  // }
  let attrs = [];

  // 有商品属性
  if (properties.value.length > 0) {
    let properties = skuData.selectedSkuComb.properties;
    properties.forEach((item, index) => {
      if (item.v) {
        attrs.push({
          id: item.v[0].id,
          name: item.v[0].name,
          price: item.v[0].price,
        });
      }
      return false;
    });
  }
  console.log(attrs.map((attr) => attr.name).toString());
  console.log(proid.value);
  console.log(attrs.toString());
  // 生成一个字符串格式的 name 值数组
  const nameString = attrs.map((attr) => attr.name).toString();
  const nums = skuData.selectedNum;
  console.log(nums);
  const priceArray = attrs.map((attr) => attr.price);
  // 计算总价格
  const totalPrice =
    attrs.reduce((acc, attr) => acc + attr.price, 0) * selectedNum;

  // const price=skuData.selectedSkuComb.price
  // return false;
  proxy.$router.push({
    path: "/product/confirms",
    query: {
      proid: proid.value.toString(),
      attrs: attrs.map((attr) => attr.id).toString(), // 只传 id
      busid: LoginUser.id,
      skuData: JSON.stringify(skuData),
      names: nameString, // 传 name 值,,
      nums: nums,
      totalPrice: totalPrice,
    },
  });
};
// 发起拼团
const teamAdd = () => {

  SkuShow.value = false

  if (JSON.stringify(LoginUser) == '{}') {
    toast('未登陆，请先去登陆');
    proxy.$router.push('/business/login')
  }

  let skuData = SkuRef.value.getSkuData()

  //购买数量 
  let selectedNum = skuData.selectedNum

  if (selectedNum <= 0) {
    error('数量不能为小于0');
    return false;
  }

  //判断是否有选择规格
  if (properties.value.length > 0 && !skuData.selectedSkuComb) {
    error('请选择商品规格')
    return false;
  }

  let relationids = []

  // 有商品属性
  if (properties.value.length > 0 && skuData.selectedSkuComb) {
    let properties = skuData.selectedSkuComb.properties
    properties.forEach((item, index) => {
      if (item.v) {
        var id = item.v[0] ? item.v[0].id : 0;
        relationids.push({
          id: id,
          name: item.v[0].name ?? '',
          price: item.v[0].price
        })
      }
      return false
    })
  }

  proxy.$cookies.set("relationids", JSON.stringify(relationids));

  proxy.$router.push({
    path: '/team/add',
    query: {
      proid: proid.value,
      nums: selectedNum
    }
  })

}
const rateInfo = ref({});
const rateavg = ref(0);
const getRateInfoData = async () => {
  let result = await Api.ProductRateinfo({
    proid: proid.value,
    busid: LoginUser.id ?? 0,
  });
  console.log(result);
  if (result.code == 1) {
    rateInfo.value = result.data.rateinfo;
    rateavg.value = Number(result.data.rateavg);
    console.log(rateInfo.value);
  }
};
</script>
<style>
.van-share-sheet__options {
  justify-content: center;
}

.van-tabs__nav--card {
  margin: 0;
}
</style>